import express from 'express';
import moment from 'moment';
import Sequelize from 'sequelize';
import { User } from '../../modal/index'; // 数据库实体类
import { statusList, sequelizeStatus } from '../../common/status'; // 状态码对照
import { checkPermission, aesEncrypt, addMoney, sendMuban } from '../../utils/utils'; // 工具类
import baseDao from '../../lib/baseDao'; // 用于获取实例化的sequelize
import CONFIG from '../../../config/config.config'; // 全局配置

const router = express.Router();
const minLevel = 0; // 允许调用接口的最低等级

router.post('/', async function (Request, Response, next) {
  let param = Request.body
  // 权限校验
  await checkPermission(Request, Response, minLevel).then(res => {
    param.userId = res.id
    param.openId = res.openId
  })
  
  if(!/^[0-9]{18}$/.test(param.tradeParentId)){
    Response.status(300).send({ message: '请输入长度18位的订单编号' });
  }
  
  if (param.formId) {
    let mubanParam = {
      page: param.page, // 点击模板跳转页面
      formId: param.formId,
      openId: param.openId,
      templateId: CONFIG.bindOrderId, // 绑定成功通知ID
      data: {
        keyword1: {
          value: '恭喜，订单绑定成功'
        },
        keyword2: {
          value: moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
        },
        keyword3: {
          value: `注意订单号只需绑定一次，后续通过小程序转链下单将会自动结算积分返利`
        },
      }
    }
    sendMuban(mubanParam, Response) // 发送模板消息
  }
  
  User.Modal.update({
    tradeParentId: (param.tradeParentId).substring(12,18), // 截取订单号后6位
  }, {
      where: {
        id: param.userId,
      },
    }).then(res => {
      Response.json({
        data: "",
        message: "success"
      });
    }).catch(async err => {
      console.log(err)
      Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
    });

});

module.exports = router;